package blow.sky.quoted.filter;

import blow.sky.quoted.response.TokenErrorResponse;
import blow.sky.quoted.utils.BearTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description 拦截器
 * @Author sun
 * @Date 2021/6/2 20:06
 */

@Order(1)
@WebFilter(filterName = "tokenFilter", urlPatterns = {"/api/request/*", "/api/response/*", "/api/info/*", "/api/ocr/*"})
public class TokenFilter implements Filter
{
    @Autowired
    private BearTokenUtil tokenUtil;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
    {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer "))
        {
            token = token.substring(7);
            // token = token.split("\\s+")[1];
        }
        if (tokenUtil.verifyToken(token) != null)
        {
            filterChain.doFilter(request, response);
            return;
        }
        response.setContentType("application/json; charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(new TokenErrorResponse("fail", "Token Verify Fail.").toString());
        response.flushBuffer();
    }
}
